/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Canadian Weather.
 *
 * The Initial Developer of the Original Code is
 *   George Bradt.
 *
 * Portions created by the Initial Developer are Copyright (C) 2011
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   George Bradt.
 *
 * Credits:
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

var CanWeatherRadar = {
    imageDivList: [],
    imageList: [],
    imageRainList: [],
    imageSnowList: [],
    frameCount: 0,
    nextFrame: 0,
    previousFrame: 0,
    stationCode: '',
    srcImageBase: 'http://dd.weatheroffice.ec.gc.ca/radar/PRECIPET/GIF/',
    
    updateNode: function (aElement, aContent) {
        // Shallow clone will not copy the content of the element.
        var newElement = aElement.cloneNode(false);

        // Insert the cloned element before the original.
        aElement.parentNode.insertBefore(newElement, aElement);

        // Remove the original element.
        aElement.parentNode.removeChild(aElement);

        // Append new content.
        newElement.appendChild(aContent);
    },
    
    initImages: function () {
        if ( CanWeatherRadar.imageRainList.length == 0 ) {
            CanWeatherRadar.imageList = CanWeatherRadar.imageSnowList;
            document.getElementById('canw-snow').checked = true;
            document.getElementById('canw-rain').disabled = true;
        }
        else if ( CanWeatherRadar.imageSnowList.length == 0 ) {
            CanWeatherRadar.imageList = CanWeatherRadar.imageRainList;
            document.getElementById('canw-rain').checked = true;
            document.getElementById('canw-snow').disabled = true;
        }
        else {
            CanWeatherRadar.imageList = ( document.getElementById('canw-rain').checked ) ?
                    CanWeatherRadar.imageRainList : CanWeatherRadar.imageSnowList;
        }
        
        CanWeatherRadar.frameCount = CanWeatherRadar.imageList.length;
        var image, imageDate, date;
        
        for ( let i = 0; i < CanWeatherRadar.frameCount; i++ ) {
            // Set src attribute for each img element.
            image = document.getElementById('canw-image' + i);
            image.setAttribute('src', CanWeatherRadar.srcImageBase + CanWeatherRadar.stationCode +
                    '/' + CanWeatherRadar.imageList[i]);
            
            // Display date and time for each image.
            date = new Date(CanWeatherRadar.imageList[i].slice(0,12).replace(
                    /^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)$/,
                    '$4:$5 +0000 $2/$3/$1'));
            imageDate = document.getElementById('canw-imageDate' + i);
            CanWeatherRadar.updateNode(imageDate, document.createTextNode(date.toLocaleString()));
        }
    
        if  ( CanWeatherRadar.imageDivList.length == 0 ) {
            for ( let i = 0; i < CanWeatherRadar.frameCount; i++ ) {
                CanWeatherRadar.imageDivList.push(document.getElementById('canw-wrapper' + i));
            }
        }
    },

    animate: function () {
        --CanWeatherRadar.nextFrame;
        CanWeatherRadar.previousFrame = ( CanWeatherRadar.nextFrame == CanWeatherRadar.frameCount - 1 ) ?
                0 : CanWeatherRadar.nextFrame + 1;
        
        if ( CanWeatherRadar.nextFrame >= 0 ) {
            CanWeatherRadar.imageDivList[CanWeatherRadar.nextFrame].style.zIndex = 1;
            CanWeatherRadar.imageDivList[CanWeatherRadar.previousFrame].style.zIndex = 0;
            window.setTimeout(function() { CanWeatherRadar.animate(); }, 1000);
        }
    }
};

// Handle user-defined event emitted from add-on code after site data is retrieved and parsed.
// Initialize panel elements.
self.port.on('show', function(aImageRainList, aImageSnowList, aRadarOptions) {
    CanWeatherRadar.imageRainList = aImageRainList;
    CanWeatherRadar.imageSnowList = aImageSnowList;
    
    if ( CanWeatherRadar.stationCode != aRadarOptions.stationCode ) {
        CanWeatherRadar.stationCode = aRadarOptions.stationCode;
        
        // Header.
        var text = aRadarOptions.stationName + ' (' + CanWeatherRadar.stationCode + ')'; 
        CanWeatherRadar.updateNode(document.getElementById('canw-name'), document.createTextNode(text));
            
        // Default cities overlay.
        var defaultCitiesURL =
                'http://weather.gc.ca/cacheable/images/radar/layers/default_cities/' +
                CanWeatherRadar.stationCode.toLowerCase() +
                '_towns.gif';
                
        var defaultCities = document.getElementById('canw-defaultCities');
        defaultCities.setAttribute('src', defaultCitiesURL);
    }
    
    CanWeatherRadar.initImages();
});

// Add event listener to our Animate button.
document.getElementById('canw-buttonAnimate').addEventListener('click', function(aEvent) {
    CanWeatherRadar.nextFrame = CanWeatherRadar.frameCount;
    CanWeatherRadar.animate();
}, true);

// Add event listener to our Reload button.
document.getElementById('canw-buttonReload').addEventListener('click', function(aEvent) {
    CanWeatherRadar.initImages();
}, true);

// Add event listener to our Ok button.
document.getElementById('canw-buttonOk').addEventListener('click', function(aEvent) {
    self.port.emit('ok-click');
    aEvent.preventDefault();
}, true);
